import JoiOrig from 'joi';
import { NODE_LABEL_ID_MAP } from '../../../../common/constants';

const Joi = JoiOrig.extend(joi => ({
	type: 'number',
	base: joi.number(),
	coerce(value) {
		let ret = value || 0;
		try {
			ret = parseFloat(ret, 10);
			return { value: ret || 0 };
		} catch (error) {
			return { value: 0 };
		}
	},
}));

export const schema = Joi.object()
	.rename('resp_avg', 'respAvg')
	.keys({
		tid: Joi.string().required(),
		respAvg: Joi.number(),
		detail: Joi.array().items(
			Joi.object()
				.rename('resp_time', 'totalTime')
				.rename('download_time', 'downloadTime')
				.rename('download_speed', 'downloadSpeed')
				.rename('status_code', 'statusCode')
				.rename('dns_time', 'dnsTime')
				.rename('content_len', 'contentLength')
				.rename('connect_time', 'connectTime')
				.rename('response_time', 'respTime')
				.rename('ssl_shake_time', 'sslShakeTime')
				.rename('header', 'response')
				.rename('loss_rate', 'lossRate')
				.rename('area', 'node', { alias: true })
				.keys({
					// IP
					ip: Joi.string().allow(''),
					// 监测点
					area: Joi.string().required(),
					node: Joi.string().required(),
					// 响应总时间
					totalTime: Joi.number().default(0).required(),
					// 丢包率
					lossRate: Joi.number(),
					// 内容下载时间
					downloadTime: Joi.number().precision(2),
					downloadSpeed: Joi.number().precision(2),
					// 响应状态码
					statusCode: Joi.number().precision(2),
					// DNS解析时间
					dnsTime: Joi.number().precision(2),
					// 响应长度
					contentLength: Joi.number().precision(2),
					// 连接耗时
					connectTime: Joi.number().precision(2),
					// 响应耗时
					respTime: Joi.number().precision(2),
					// SSL握手时间
					sslShakeTime: Joi.number().precision(2),
					// 响应头
					response: Joi.string().allow(''),
				})
				.custom(value => ({
					...value,
					node: NODE_LABEL_ID_MAP[value.node],
					response: value.response
						? Object.entries(JSON.parse(value.response || '{}'))
								.map(([key, val]) => `${key}: ${val}`)
								.join('\n')
						: '',
				}))
				.unknown()
		),
	})
	.unknown();

export default function responseValidate(response) {
	return (
		schema.validate(response, { convert: true })?.value || {
			warnings: [],
			addition: {},
		}
	);
}
